package com.ruoyi.network;



import com.ruoyi.common.utils.HexUtil;
import com.ruoyi.network.message.ReceivedMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@ChannelHandler.Sharable
public class CustomServer2Handler extends ChannelInboundHandlerAdapter {

    @Autowired
    private OnlineDeviceManager onlineDeviceManager;

    @Autowired
    private MessageBus messageBus;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //三次握手以后
        System.out.println("连接："+ctx.channel().remoteAddress());


    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {


        System.out.println("设备离线");
        //断开连接   四次挥手
        onlineDeviceManager.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        System.out.println("设备处理消息遇到异常"+cause.getMessage());
        //关闭连接
        onlineDeviceManager.remove(ctx.channel());
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //将接收的数据ByteBuf转换为十六进制字符串
        ByteBuf data = (ByteBuf)msg;
        byte[] req = new byte[data.readableBytes()];
        data.readBytes(req);
        //byte[] 转16进制
        String hex = HexUtil.bytesToHexString(req);

        Date date = new Date();
        String dateStr = dateFormat.format(date);

        System.out.println("服务端接到客户端数据"+dateStr+"："+hex);

        ReceivedMessage message= new ReceivedMessage(hex);

        onlineDeviceManager.add(message.getDeviceCode(), ctx.channel());

        if(onlineDeviceManager.checkDeviceOnline(message.getDeviceCode())==false){
            return;
        }

        //messageBus.handleReceivedMessage(message);
        messageBus.asyncHandleReceivedMessage(message);

        System.out.println("后续..............");
    }



    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
